<template>
  <div class="dashboard-container" id="combo-app">
    <div class="container">
      <!-- 搜索栏 -->
      <div class="tableBar">
        <el-input
            v-model="input"
            placeholder="请输入套餐名称"
            style="width: 250px"
            clearable
            @keyup.enter="handleQuery"
        >
          <i slot="prefix" class="el-input__icon el-icon-search" style="cursor: pointer" @click="init"></i>
        </el-input>

        <div class="tableLab">
          <span class="span-btn delBut non" @click="deleteHandle('批量')">批量删除</span>
          <span class="span-btn blueBug non" @click="statusHandle('1')">批量启售</span>
          <span class="span-btn delBut non" @click="statusHandle('0')">批量停售</span>
          <el-button type="primary" @click="addSetMeal('add')">+ 新建套餐</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" stripe class="tableBox" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="25"></el-table-column>
        <el-table-column prop="name" label="套餐名称"></el-table-column>
        <el-table-column prop="image" label="图片" align="center">
          <template #default="{ row }">
            <el-image
                style="width: auto; height: 40px;"
                :src="getImage(row.image)"
                :preview-src-list="[ `/common/download?name=${row.image}` ]"
            >
              <template #error>
                <img src="../../assets/images/noImg.png" style="width: auto; height: 40px;" />
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="套餐分类"></el-table-column>
        <el-table-column prop="price" label="套餐价">
          <template #default="{ row }">￥{{ row.price / 100 }}</template>
        </el-table-column>
        <el-table-column label="售卖状态">
          <template #default="{ row }">{{ row.status === 0 ? '停售' : '启售' }}</template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间"></el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template #default="{ row }">
            <el-button
                type="text"
                size="small"
                class="blueBug"
                @click="addSetMeal(row.id)"
            >修改</el-button>

            <el-button
                type="text"
                size="small"
                class="blueBug"
                @click="statusHandle(row)"
            >
              {{ row.status === 0 ? '启售' : '停售' }}
            </el-button>

            <el-button
                type="text"
                size="small"
                class="delBut non"
                @click="deleteHandle('单删', row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          class="pageList"
          :page-sizes="[10, 20, 30, 40]"
          v-model:page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="counts"
          v-model:current-page="page"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  getSetmealPage,
  deleteSetmeal,
  setmealStatusByStatus
} from '@/api/combo'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 数据定义
const input = ref('')
const counts = ref(0)
const page = ref(1)
const pageSize = ref(10)
const tableData = ref([])
const checkList = ref([])

// 初始化数据
const init = async () => {
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    name: input.value || undefined
  }

  try {
    const res = await getSetmealPage(params)
    if (res.code === 1) {
      tableData.value = res.data.records || []
      counts.value = res.data.total
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (err) {
    ElMessage.error('请求出错了：' + err)
  }
}

// 获取图片路径
const getImage = (image) => {
  return `/common/download?name=${image}`
}

// 删除操作
const deleteHandle = (type, id) => {
  if (type === '批量' && !id) {
    if (checkList.value.length === 0) {
      return ElMessage.error('请选择删除对象')
    }
  }

  ElMessageBox.confirm(
      '确认删除该套餐？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    const ids = type === '批量' ? checkList.value.join(',') : id
    deleteSetmeal(ids).then(res => {
      if (res.code === 1) {
        ElMessage.success('删除成功！')
        handleQuery()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    }).catch(err => {
      ElMessage.error('请求出错了：' + err)
    })
  })
}

// 状态变更
const statusHandle = (row) => {
  let params = {}

  if (typeof row === 'string') {
    if (checkList.value.length === 0) {
      return ElMessage.error('请先勾选操作套餐！')
    }
    params = {
      ids: checkList.value.join(','),
      status: row
    }
  } else {
    params = {
      ids: row.id,
      status: row.status === 1 ? 0 : 1
    }
  }

  ElMessageBox.confirm('确认更改该套餐状态?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    setmealStatusByStatus(params).then(res => {
      if (res.code === 1) {
        ElMessage.success('套餐状态已更改成功！')
        handleQuery()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    }).catch(err => {
      ElMessage.error('请求出错了：' + err)
    })
  })
}

// 批量选择处理
const handleSelectionChange = (val) => {
  checkList.value = val.map(item => item.id)
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  init()
}

const handleCurrentChange = (val) => {
  page.value = val
  init()
}

const handleQuery = () => {
  page.value = 1
  init()
}

onMounted(() => {
  init()
})
</script>

<style scoped>
/* 可保留原有样式或提取到全局 */
.dashboard-container .notAdmin::after {
  border: 0 !important;
}

.continue {
  margin-left: 10px;
}
</style>
